package main

import "fmt"

func generateMatrix(n int) [][]int {
	var results [][]int
	for i := 0; i < n; i++ {
		inline := make([]int, n)
		results = append(results, inline)
	}

	var tmp [][]bool
	for i := 0; i < n; i++ {
		inline := make([]bool, n)
		tmp = append(tmp, inline)
	}

	q := 0
	i, j := 0, 0
	i0, j0 := 0, 0
	for {
		q = q + 1
		results[i][j] = q
		tmp[i][j] = true

		if q == n*n {
			break
		}

		if i == 0 && j == 0 {
			j = j + 1
			continue
		}

		if j > j0 {
			if j+1 < n && tmp[i][j+1] == false {
				j0 = j
				j = j + 1
				continue
			}
			if i+1 < n && tmp[i+1][j] == false {
				i0 = i
				i = i + 1
				continue
			}
			if j-1 >= 0 && tmp[i][j-1] == false {
				j0 = j
				j = j - 1
				continue
			}
			if i-1 >= 0 && tmp[i-1][j] == false {
				i0 = i
				i = i - 1
				continue
			}
		}

		if j < j0 {
			if j-1 >= 0 && tmp[i][j-1] == false {
				j0 = j
				j = j - 1
				continue
			}
			if i-1 >= 0 && tmp[i-1][j] == false {
				i0 = i
				i = i - 1
				continue
			}
			if j+1 < n && tmp[i][j+1] == false {
				j0 = j
				j = j + 1
				continue
			}
			if i+1 < n && tmp[i+1][j] == false {
				i0 = i
				i = i + 1
				continue
			}
		}
		if i > i0 {
			if i+1 < n && tmp[i+1][j] == false {
				i0 = i
				i = i + 1
				continue
			}
			if j-1 >= 0 && tmp[i][j-1] == false {
				j0 = j
				j = j - 1
				continue
			}
			if i-1 >= 0 && tmp[i-1][j] == false {
				i0 = i
				i = i - 1
				continue
			}
			if j+1 < n && tmp[i][j+1] == false {
				j0 = j
				j = j + 1
				continue
			}
		}
		if i < i0 {
			if i-1 >= 0 && tmp[i-1][j] == false {
				i0 = i
				i = i - 1
				continue
			}
			if j+1 < n && tmp[i][j+1] == false {
				j0 = j
				j = j + 1
				continue
			}
			if i+1 < n && tmp[i+1][j] == false {
				i0 = i
				i = i + 1
				continue
			}
			if j-1 >= 0 && tmp[i][j-1] == false {
				j0 = j
				j = j - 1
				continue
			}
		}
		break

	}
	return results
}

func main() {
	fmt.Print(generateMatrix(3))
}
